package com.leimo.demo.config;

import brave.context.slf4j.MDCScopeDecorator;
import brave.propagation.CurrentTraceContext;
import brave.propagation.CurrentTraceContext.ScopeDecorator;
import brave.spring.beans.CurrentTraceContextFactoryBean;
import brave.spring.beans.TracingFactoryBean;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import zipkin2.reporter.AsyncReporter;
import zipkin2.reporter.beans.AsyncReporterFactoryBean;
import zipkin2.reporter.beans.OkHttpSenderFactoryBean;
import zipkin2.reporter.okhttp3.OkHttpSender;

@Configuration
public class ProviderZipkinConfig {

  @Bean
  public OkHttpSenderFactoryBean okHttpSenderFactoryBean(){
    OkHttpSenderFactoryBean okHttpSenderFactoryBean = new OkHttpSenderFactoryBean();
    okHttpSenderFactoryBean.setEndpoint("http://localhost:9411/api/v2/spans");
    return okHttpSenderFactoryBean;
  }

  @Bean
  public AsyncReporterFactoryBean asyncReporterFactoryBean(OkHttpSender sender){
    AsyncReporterFactoryBean asyncReporterFactoryBean = new AsyncReporterFactoryBean();
    asyncReporterFactoryBean.setSender(sender);
    asyncReporterFactoryBean.setCloseTimeout(500);
    return asyncReporterFactoryBean;
  }

  @Bean
  public CurrentTraceContextFactoryBean currentTraceContextFactoryBean(){
    ScopeDecorator scopeDecorator = MDCScopeDecorator.create();
    CurrentTraceContextFactoryBean currentTraceContextFactoryBean = new CurrentTraceContextFactoryBean();
    currentTraceContextFactoryBean.setScopeDecorators(Lists.newArrayList(scopeDecorator));
    return currentTraceContextFactoryBean;
  }

  @Bean(name = "tracing")
  public TracingFactoryBean tracingFactoryBean(OkHttpSender sender, CurrentTraceContext currentTraceContext) throws Exception {
    AsyncReporterFactoryBean factoryBean = this.asyncReporterFactoryBean(sender);
    AsyncReporter reporter = (AsyncReporter)(factoryBean.getObject());
    TracingFactoryBean tracingFactoryBean = new TracingFactoryBean();
    tracingFactoryBean.setLocalServiceName("hello-service-provider2");
    tracingFactoryBean.setSpanReporter(reporter);
    tracingFactoryBean.setCurrentTraceContext(currentTraceContext);
    return tracingFactoryBean;
  }
}
